/**
 * @file The internal error handler 
 * 
 * @author Steve Gao<gaofu@parllay.com>
 */
const BaseHandler = require('../base-handler');

const {WebRequestError} = require('../../../errors');

const {HTTP_VERBS, HTTP_STATUSES, ApplicationEvents, CriticalErrors} = require('../../../constants');

/**
 * The internal error handler
 * 
 * @description
 * When our system meet some internal error, we need use this handler to handle
 * 
 * @class InternalErrorHandler
 * @extends {BaseHandler}
 */
class InternalErrorHandler extends BaseHandler {

    doERROR(error, request, response, next) {
        request.requestData.error = {
            message: error.message,
            stack: error.stack
        };
        request.requestData.end_time = new Date();
        this.Server.reportError(ApplicationEvents.WEB_REQUEST_ERROR, 
            new WebRequestError(`Failed to handle request [${request.url}], error happened:`, 
                                CriticalErrors.WEB_REQUEST_ERROR, 
                                request.requestData));
        //TODO: If this error happen, we should notify the developers or ops team
        response.status(HTTP_STATUSES.INTERNAL_ERROR).render('common/internal-error');
    }

    setup() {
        this.registerVerb(HTTP_VERBS.ERROR, this.doERROR);
    }
}

module.exports = InternalErrorHandler;